﻿/* Get the number of moves. */
function getMoves()
{
	if ( wave.getState() )
	{
		return parseInt( wave.getState().get( "moves", "0" ) );
	}
	else
	{
		return 0;
	}
}

function TalkBack(){
	wave.getState().submitDelta({ TB_Req : "1" });	
}

function getCost()
{
	if ( wave.getState() )
	{
		return parseFloat( wave.getState().get( "cost", "0" ) );
	}
	else
	{
		return 0;
	}
}

function getAggCost()
{
	if ( wave.getState() )
	{
		return parseFloat( wave.getState().get( "agg_cost", "0" ) );
	}
	else
	{
		return 0;
	}
}

function getAggPrize()
{
	if ( wave.getState() )
	{
		return parseInt( wave.getState().get( "agg_prize", "0" ) );
	}
	else
	{
		return 0;
	}
}

//this function will reset the form and then run the totomat
function totomat(){
	answer=confirm("filling the form automatically will delete all current filled out squares. are you sure you want to proceed?");
	if (answer !=0){ 
		doReset(1);
		setTimeout('runTotomat()',500);
	}
}

//this function will do the actual randomization
function runTotomat(){
	var game = gameState();
	var new_account=accountState();
	var temp;
	for (i=0;i<16;i++){
		temp=Math.floor(Math.random()*3);
		game[i][temp]=!game[i][temp];
	}

	//for debugging
	/*for (i=0;i<16;i++){
					for (j=0;j<3;j++){
					alert(game[i,j]);
					}
				}*/


	var cost=new Number();
	var numOfCols= getCols(game)[16];
	cost=(numOfCols*2.8).toFixed(2);
	wave.getState().submitDelta( { "game"  : wave.util.printJson( game ),
		"cost" : cost});

	//setTimeout('runTotomatTest()',2000);
}

//this function was created for debug pruposes
function runTotomatTest(){
	var game = gameState();
	for (i=0;i<16;i++){
		for (j=0;j<3;j++){
			alert(game[i][j]);
		}
	}
}

/* 1 React to a cell click. */
function cellClick( row, col ){
	
	if(IsRightTime(getDateFromState("cellClickLowerLimit"),getDateFromState("cellClickUpperLimit"))){ // added to lock availablity of form
		// Get the current state of play.
		var game = gameState();
		var name=wave.getViewer().getDisplayName();
		var num=0;
		var cost=new Number();
		var parId=wave.getViewer().getId();
		var new_account=accountState();
		var agreeFlag=0;
		// Make the move.
		//if (row==12)
			//RefreshData(1);
		if (col<3)   {
			//calculate number of cols
			game[row][col] = !game[row][col];
			var colsArray=getCols(game);
			var numOfCols= colsArray[16];
			var legal=legalFillout(colsArray[18],colsArray[19]);

			//checking legality of the fillout
			if (legal==10){
				if (game[row][col]){
					updateServlet(1,row,col);
					new_account[row][col]=parId;
					agreementClick(row,col,game,1);
				}
				else {
					new_account[row][col]="";
					updateServlet(0,row,col);
					agreementClick(row,col,game,0);
				}
				cost=(numOfCols*2.8).toFixed(2);	
				// Write the state of play back to the Wave.
				wave.getState().submitDelta( { "game"  : wave.util.printJson( game ),
					"moves" : getMoves() + 1,
					"cost" : cost,
					"account":wave.util.printJson(new_account)});
			}
			else {
				game[row][col] = !game[row][col];
				//will need to replace this alert with a box
				alertFillout(legal);				 
			}
		}
	}// close isRightTime
} //close function


// 	this function represents the clicks in the personal form of the viewer.
//	it updates the agreement array,the viewer's personal inner form, and (if necessary) the actual form
// when there is no one voting for a square in his inner form, the actual form will turn off.
// this funtion can accept a game element (16x3) and a wanted value (this for efficiant use in cellClick).
// if no game and value were givan (regular agreementClick) it will retrieve the needed values on the fly.
// to disable the use of givan values use (givenGame=false ,givenVal>1) as input.
function agreementClick(row,col,givenGame,givenVal){
	var isEmptyFlag = 1;
	var game = (givenGame==false ? gameState() : givenGame);
	//set the the viewer's profile
	var parId=wave.getViewer().getId();
	var profile=profileState(parId);
	if(col==3){//clear profile mode
		for(k=0 ; k<3 ; k++){
			profile[row][k]=0
		}
	}
	else{//regular agreementClick
		var val=(givenVal>1 ? (profile[row][col]==1?0:1) : givenVal);
		profile[row][col]=val;
	}
	//set the game (the global form) and agreement
	var gameProfile=getGameProfile(row,parId,profile);
	var agreement=agreementState();
	agreement[row]=0;
	for (col=0;col<3;col++){		
		//set the form if needed
		if ((gameProfile[col].length ==0)&&(game[row][col])){
			game[row][col]=false;
		}
		//set the agreement
		if((gameProfile[col].length!=0)&&(!game[row][col])){
			agreement[row]=1;
		}
		else if (game[row][col]){isEmptyFlag=0;}
	}
	if (isEmptyFlag==1){agreement[row]=0;} //no disagreement when nothing is marked
	
	delta = {};
    delta[parId] = wave.util.printJson(profile);
	delta["game"] = wave.util.printJson(game);
	delta["agreement"] = wave.util.printJson(agreement);
	//update agreement
	//alert(agreement);
	wave.getState().submitDelta(delta); 
}

//this function refreshes the display of the agreement bar
function refreshAgreement(){
	var agreement = agreementState();
	for(i=0;i<16;i++){
		document.getElementById("agree"+i).setAttribute("class",(agreement[i] ? "disagree_button" : "agree_button"));
	}
}

function refreshAgreementDivs(){
	var GP;
	for(l=0;l<16;l++){
		GP = getGameProfile(l,0,0);
		document.getElementById("agreement_div"+l).innerHTML = "<table cellspacing='2' border='0' cellpading='3'>"+CreateSingleGameTable(GP,l)+"</table>";
	}
}

function clearAllProfiles(){
	var par=wave.getParticipants();
	var delta = {};
	//reste the agreement Array
	delta["agreement"] = wave.util.printJson(defaultAgreement());
	//reset the personal profiles
	var newProfile = wave.util.printJson(defaultProfile());
	for (i = 0; i < par.length;i++){
		alert(newProfile);
		delta[par[i].getId()] = newProfile;
	}
	wave.getState().submitDelta(delta);
}

//This function checks whther there is a dispute regarding game # row (that is, there is someone that thinks something that is not reflected in the form ,and the form is not empty for that game) 
function checkAgreement(row,newParId,newProfile,game){
	var agreement=agreementState();
	var gameProfile=getGameProfile(row,newParId,newProfile);
	var isEmptyFlag=1;
	agreement[row]=0;
	for (col=0;col<3;col++){
		if ((gameProfile[col].length!=0)&&(!game[row][col])){
			agreement[row]=1;
		}
		if (game[row][col]){
			isEmptyFlag=0;
		}
	}
	if (isEmptyFlag==1)
		agreement[row]=0;
	wave.getState().submitDelta( { "agreement"  : wave.util.printJson( agreement )});
	return agreement[row];
}

//This function gets: row= a game # and ; newParId= the id of the participant whose profile was just updated; newProfile= the new profiel of newParId (that is not updated in the state yet)
//returns an array of concatenated Id's of participants (divided by #), 
//such that the y cell holds the participants ids that have marked the y column for this game 
//with the exception that the fourth is for neutral participants 
function getGameProfile(row,newParId,newProfile){
	var gameProfile=[new Array(),new Array(),new Array(),new Array()]; 
	var par=wave.getParticipants();
	for (j_new = 0;j_new < par.length;j_new++){
		var flag=0;
		var parId=par[j_new].getId();
		var parPic="<img src=" + par[j_new].getThumbnailUrl() + " style='height:42px;width:42px'>"; 
		var profile=profileState(parId);
		if (parId==newParId)
			profile=newProfile;
		for (col=0;col<3;col++){
			if (profile[row][col]==1){
				flag=1;
				gameProfile[col].push(parPic);
			}
		}
		if (flag==0)
			gameProfile[3].push(parPic);
	}		
	return gameProfile;
}
/*//this function builds the table you see when looking at the personal form games
function CreateSingleGameTable(gameProfile,gameNum){
	var userProfile = profileState(wave.getViewer().getId());
	var maxCol = FindMaxCol(gameProfile);
	//alert(maxCol);
	//alert(gameProfile);
	var HTMLgametable = "<tr><td class="+(userProfile[gameNum][0]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",0,false,2)>2</td><td class="
										+(userProfile[gameNum][1]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",1,false,2)>X</td><td class="
										+(userProfile[gameNum][2]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",2,false,2)>1</td><td class='solve_dispute' onclick=agreementClick("+gameNum+",3,false,2)></td></tr>";
	for(i=0;i<maxCol;i++){
		HTMLgametable = HTMLgametable + "<tr>";
		for (j=0;j<4;j++){
			//alert(HTMLgametable);
			//alert(gameProfile[j].length);
			if(gameProfile[j].length>i){
				HTMLgametable = HTMLgametable + "<td>" + gameProfile[j][i] + "</td>";
			//	alert("i1="+i+" j1="+j);
			}
			else{
				HTMLgametable = HTMLgametable + "<td></td>";
			//	alert("i2="+i+" j2="+j);
			}	
		}
		HTMLgametable = HTMLgametable + "</tr>";
	}
	return HTMLgametable;
}*/
//this function builds the table you see when looking at the personal form games
function CreateSingleGameTable(gameProfile,gameNum){
	var userProfile = profileState(wave.getViewer().getId());
	var maxCol = FindMaxCol(gameProfile);
	reverseArray(gameProfile, 4);
	
	var HTMLgametable = "<tr><td><div class='solve_dispute' onclick=agreementClick("+gameNum+",3,false,2)><div class='solve_dispute_left'>נייטרלי</div><div class='solve_dispute_right'>&nbsp;</div></td>"+
                    "<td width='44' align='center'><div class="+(userProfile[gameNum][2]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",2,false,2)>1</div></td>"+
                    "<td width='44' align='center'><div class="+(userProfile[gameNum][1]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",1,false,2)>X</div></td>"+                    
                    "<td width='44' align='center'><div class="+(userProfile[gameNum][0]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",0,false,2)>2</div></td></tr>";
	HTMLgametable = HTMLgametable + "<tr><td colspan='4'><h3>מה חושבים החבר'ה?</h3></td></tr>";
	for(i=0;i<maxCol;i++){		
		HTMLgametable = HTMLgametable + "<tr>";
		for (j=0;j<4;j++){
			if(gameProfile[j].length>i){
				HTMLgametable = HTMLgametable + "<td align='center'>" + gameProfile[j][i] + "</td>";
			}
			else{
				HTMLgametable = HTMLgametable + "<td></td>";
			}	
		}
		HTMLgametable = HTMLgametable + "</tr>";
	}
	return HTMLgametable;
}

// a help function in building the disagreement table in CreateSingleGameTable.
function FindMaxCol(gameProfile){
	var max = 0;
	var temp = 0;
	//var tempArr = null;
	for(i=0;i<gameProfile.length;i++){
		temp = gameProfile[i].length;
		max = (temp > max ? temp : max);
	}
	return max;
}

function updateServlet(update,row,col){
	var servlet = "http://gilivaturitest.appspot.com/totoChartsUpdate";                //the name (URI) of your servlet
	//var arg = update+'#'+row+'#'+col;               //any attributes you want to send
	var req = servlet + "?" +update+col+row;            //compiling the request

	addrequest(req); 
	//calls the addrequest function
	//request.onreadystatechange = function(){  //this is used to listen for changes in the request's status
	//do something with the response
}

function addrequest(req) {
	try {                                     //create a request for netscape, mozilla, opera, etc.
		request = new XMLHttpRequest();
	}catch (e) {

		try {                                 //create a request for internet explorer
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}catch (e) {                           //do some error-handling
			alert("XMLHttpRequest error: " + e);
		}
	}

	request.open("GET", req, true);       //prepare the request
	request.send(null);                       //send it
	return request;                           //return the request
}

function isDone(game){
	var sub_count = 0;
	var row_count = 0;
	for ( row = 0; row < 16; row++ )
	{   sub_count = 0;
	for ( col = 0; col < 3; col++ ){
		if ( game[ row ][ col ] ) 
			sub_count=sub_count+1;
	}
	if (sub_count>0)
		row_count=row_count+1;

	}
	row_count=16-row_count;
	return row_count;

}

/* this function returns an array where:
		results[0..15]=the number of marks in each row
		results[16]= total number of colums
		results[17]= total number of singles
		results[18]= total number of doubles
		results[19] total number of triplets */
function getCols(game){
	var doubles=0;
	var triplets=0;
	var singles=0;
	var totalCols=0;
	var results=new Array();
	for (i=0;i<16;i++){
		rowmarks=calcMarksInRow(game,i);
		results[i]=rowmarks;
		if (rowmarks==1) singles++;
		if (rowmarks==2) doubles++;
		if (rowmarks==3) triplets++;
	}
	if (singles+doubles+triplets==16)
		totalCols= Math.pow(2,doubles)*Math.pow(3,triplets);
	results[16]=totalCols;
	results[17]=singles;
	results[18]=doubles;
	results[19]=triplets;

	return results;	

}

//this function calculated how many marks are in a single row
function calcMarksInRow(game,row){
	if ((game[row][0]) && (game[row][1]) && (game[row][2])) return 3;
	if ((!game[row][0]) && (!game[row][1]) && (!game[row][2])) return 0;
	if ((!game[row][0]) && (game[row][1]) && (game[row][2])) return 2;
	if ((game[row][0]) && (!game[row][1]) && (game[row][2])) return 2;
	if ((game[row][0]) && (game[row][1]) && (!game[row][2])) return 2;
	return 1;
}

function legalFillout(doubles,triplets){
	if (triplets>5) return 0;
	if ((triplets==5) && (doubles>0)) return 0;
	if ((triplets==4) && (doubles>2)) return 1;
	if ((triplets==3) && (doubles>4)) return 2;
	if ((triplets==2) && (doubles>5)) return 3;
	if ((triplets==1) && (doubles>7)) return 4;
	if ((triplets==0) && (doubles>8)) return 5;
	return 10;
}

function alertFillout(number){
	if (number==0) alert("בטור עם 5 משולשים לא ניתן לסמן כפולים");
	if (number==1) alert("בטור עם 4 משולשים ניתן לסמן לכל היותר 2 כפולים");
	if (number==2) alert("בטור עם 3 משולשים ניתן לסמן לכל היותר 4 כפולים");
	if (number==3) alert("בטור עם 2 משולשים ניתן לסמן לכל היותר 5 כפולים");
	if (number==4) alert("בטור עם משולש יחיד ניתן לסמן לכל היותר 7 כפולים");
	if (number==5) alert("בטור ללא משולשים ניתן לסמן לכל היותר 8 כפולים");
}


/***********************************NEW GENERIC FUNCTION**********************************/
/* A generic function that constructs default arrays. 					*/ 
/* s1 and s2 denote the length and the width of the array, respectively;*/
/* init_value denoted the initialization values.         				*/
function constructArray(s1,s2,init_value){
	var my_array=new Array(s1);
	for ( i = 0; i < s1; i++ ){
		if (s2>1){
			my_array[i]=new Array (s2);
			for ( j = 0; j < s2; j++ )
				my_array[i][j]=init_value;
		}
		else
			my_array[i]=init_value;
	}
	return my_array;
}
/* The initial state of a game. */          
function defaultGame(){
	return constructArray(16,3,false);
}

	function defaultOldFormList(){
		var array=new Array();
		return array;
	}
	
function defaultCorrectResultsDisplay(){
	return constructArray(16,3,0);
}
function defaultAccount(){
	return constructArray(16,3,'');
}
function defaultCorrectResults(){
	return constructArray(16,1,0); 
}
function defaultProfile(){
	return constructArray(16,3,0); 
}
function defaultAgreement(){
	return constructArray(16,1,0);
}
/* A generic function that gets some non-string object from the state*/
/* my_key denotes the key of the object in the state*/
/* my_d denotes the default function that generates the default object*/
function getSomething (my_key,my_d){
	if ( wave.getState() ){
		var my_val = eval( "(" + wave.getState().get( my_key) + ")" );
		return my_val ? my_val : my_d;
	}
	else
		return my_d;
}
/* Get the state for the current game. */
function gameState(){
	return getSomething ("game",defaultGame());
}

	function getOldFormsListFromState(){
		return getSomething("oldFormsList",defaultOldFormList());
	}

/* Get the state of the current results. */
function correctResultsDisplayState(){	
	return getSomething ( "correctResultsDisplay",defaultCorrectResultsDisplay());
}
/* Get the state of the last week results. */
function lw_correctResultsDisplayState(){
	return getSomething ("lw_correctResultsDisplay",defaultCorrectResultsDisplay());
}
/* Get the state for the last week game. */
function last_week_gameState(){	
	return getSomething ("last_week_game",defaultGame());
}
/* Get the account for the current game. */
function accountState(){	
	return getSomething ("account",defaultAccount());
}
/* Get the account for the current profile of the parId participant. */
function profileState(parId){
	return getSomething (parId,defaultProfile());
}
/* Get the state for the current agreement. */
function agreementState(){
	return getSomething ("agreement",defaultAgreement());
}

/* Get the state of the scores current game. */
function parHistoryState(){
	var par=wave.getParticipants();
	var parHistory={};
	for (i=0; i<par.length;i++){
		tmpStr=par[i].getId()+"_score";
		parHistory[tmpStr]=parScoreState(tmpStr);
		tmpStr=par[i].getId()+"_rightGuess";
		parHistory[tmpStr]=parScoreState(tmpStr);
		tmpStr=par[i].getId()+"_wrongeGuess";
		parHistory[tmpStr]=parScoreState(tmpStr);
		tmpStr=par[i].getId()+"_place";
		parHistory[tmpStr]=parScoreState(tmpStr);
	}
	return parHistory;
}

/*******************************************************************************************************************************************************
/* Get the current games column from the state */
function GamesStrState(){
	if ( wave.getState() ){
		var GamesStr = wave.getState().get( "GamesStr" );
		return GamesStr ? GamesStr : "";
	}
	else{
		return "";
	}
}

/* Get the participante's data from the state */
function parScoreState(str){
	return getSomething (str,[0]);
}

/* Get the current results column from the state as an array*/
/* (type==0) -> games results , (type==1) -> first prizes */
/*	if results are not present return []*/
function Results(type,ResultsStr){ 
	if(!ResultsStr){
		return [];
	}
	else{
		var TypesArray = ResultsStr.split("#");
		var ResultsArray = TypesArray[type].split("$");
		return ResultsArray;
	}
}

/* 	Get the recommendations from the state as an array*/
/*	(type==0) -> textual recommendations, (type==1) -> final recommendations */
function Recommendations(type){
	if ( wave.getState() ){
		var RecStr = wave.getState().get( "RecStr" );
		if(!RecStr){
			return [];
		}
		else{
			var TypesArray = RecStr.split("#");
			var RecArray = TypesArray[type].split("$");
			return RecArray;
		}
	}
	else
	{
		return [];
	}
}

//returns an array of the stat links
function StatURLsState(){
	if ( wave.getState() ){
		var StatLinksStr = wave.getState().get( "StatLinksStr" );
		if(!StatLinksStr){
			return [];
		}
		else{
			var StatArray = StatLinksStr.split("$");
			return StatArray;
		}
	}
}

/* Set the state of a cell in the display. */
function setCell( row, col, on )
{
	document.getElementById( "cell" + row + col ).className = on ? "cellOn" : "cellOff";
}

/* Do Something for each cell in the game. */
function forEachCell( f )
{
	for ( row = 0; row < 16; row++ )
	{
		for ( col = 0; col < 3; col++ )
		{
			f( row, col );
		}
	}
}

/* Refresh the grid based on the current game state. */
function refreshGrid( gameState )
{
	if(parseInt(wave.getState().get("ResultsReq"))){
		RefreshResultsDisplay();
		//display the results guide
		document.getElementById("main_symbols_table").setAttribute("class", "symbols_table");
	}
	else{		   
		forEachCell( function( row, col ) { setCell( row, col, gameState[ row ][ col ] ) } );
		//while playing no need for a results guide
		document.getElementById("main_symbols_table").setAttribute("class", "symbols_table_invisible");
	}
}

/* Get the count of cells switched on. */
function onCount( gameState )
{
	var count = 0;

	forEachCell( function( row, col ) { if ( gameState[ row ][ col ] ) count++; } );

	return count;
}


function fillingAccount(Participants,account){
	var howManyTotla_t="";
	for ( par = 0; par < Participants.length; par++ ){
		var name=Participants[par].getDisplayName();
		var id=Participants[par].getId();	
		var count=0;
		forEachCell(function(row,col){if (account[row][col]==id) count++;});
		var square_t=count==1?" square":" squares";
		var howMany_t=name+" filled "+count+square_t;
		var howManyTotla_t=howManyTotla_t+"\n"+howMany_t+". ";
	}
	return howManyTotla_t;
}


/* Update the display of number of moves. */
function refreshMoves( gameState )
{
	var moves   = getMoves();
	var moves_t = moves == 1 ? "move" : "moves";
	var counter= isDone(gameState);
	var counter_t= counter==1?" game ":" games ";

	document.getElementById( "moves" ).innerHTML =
		"After " + moves + " " + moves_t + " You still have "+ counter+counter_t+ "left to fill.";
	document.getElementById( "Who" ).innerHTML = fillingAccount(wave.getParticipants(),accountState());

}

/* After the state has changed, refresh the display. */
function stateUpdated()
{
	var game = gameState();		   
	refreshGrid( game );
	refreshMoves( game );
	refreshAgreement(); //<effi> refresh the agreement bar
	refreshAgreementDivs();//<effi> refresh the agreement personal Divs
	refreshCost();
	RefreshGames();
	//RefreshRec();  <oren> this function is no longer needed as the rec's are being fetched on the fly
	//getLastWeekInfo(); <Gili> this funtion will be triggred from the last week button.
	refreshTalkBacks(); //<effi> hope all these changes arent fucking up the code...
	gadgets.window.adjustHeight();
}

function resetGame()
{	
	answer = confirm("Do you really want to Reset");
	doReset(answer);

}

function doReset(answer){
	if (answer !=0){ 
		var par=wave.getParticipants();
		var delta = {};
		//clear the agreement Array
		delta["agreement"] = wave.util.printJson(defaultAgreement());
		//clear the personal profiles
		var newProfile = wave.util.printJson(defaultProfile());
		for (i = 0; i < par.length;i++){
			delta[par[i].getId()] = newProfile;
		}
		//clear the cost
		delta["cost"]="0";
		//clear the form's account
		delta["account"]=wave.util.printJson(defaultAccount());
		//clear the actuall board
		delta["game"]=wave.util.printJson(defaultGame());
		//clear talkbacks
		delta["TalkBackString"]="#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del"
		//submit the changes
		wave.getState().submitDelta(delta);
	}
}

/* Initialise the display. */
function init()
{

	if ( wave && wave.isInWaveContainer() )
	{
		wave.setStateCallback( stateUpdated );
	}

	_IG_AdjustIFrameHeight();								   			
	//	RefreshData(0);//get the current games
	//	RefreshData(1);//get the results
	//	RefreshData(2);//get the recommendations
	//	RefreshData(3);//get the current time
	/* Set the page displayed according to the current play mode */

	//setTimeout("getPage()",400);
	setTimeout("firstInit()",400);
	setTimeout("ResultsToState()",400);
	setTimeout("RecommendationsToState()",2000);

	gadgets.window.adjustHeight();
}


gadgets.util.registerOnLoadHandler( init );



//this function get an array and its length and reverses it
function reverseArray(results,n){
	var temp=0;
	for (i=0;i<Math.floor(n/2);i++){
		temp=results[i];
		results[i]=results[n-i-1];
		results[n-i-1]=temp;
	}
	return results;
}

/*this is a function for debugging of the checkResults function
		function testMyResults(){
		var id=wave.getState().get("idiotID");
		alert("callback"+correctResultsDisplayState()[0][0]);
		alert("callback"+correctResultsDisplayState()[0][1]);
		alert("callback"+correctResultsDisplayState()[0][2]);
		if (id==-1) alert("no idiot");
		else alert("callback:"+"idiot:"+wave.getParticipantById(wave.getState().get("idiotID")).getDisplayName());
		alert("callback:"+"guesses:"+wave.getState().get("numberOfCorrectGuesses"));
		alert("callback:"+"prize:"+wave.getState().get("prize"));
		}*/



//this function translates the TOTO's correct result to OUR col number. for example: 'x'-->1
function translateCol(col){
	//alert("original value is" +col);
	if (col==1) return 2;				
	if (col=='X') return 1;
	if (col==2) return 0;
}

//this function returns with col which is the correct results this week (in OUR terms, not TOTO terms);
function getWinnerCol(row,gamesResults){
	var returnedValue= translateCol(gamesResults[row]);
	//alert("returned value is"+returnedValue);
	return returnedValue;
}

//this function translates the TOTO's correct result Array to OUR correct results Array. for example: 'x'-->1
function translatedResultsArray(gamesResults){
	var translatedResults=new array();
	for (row=0;i<16;i++)
	{
		translatedResults[row]=translateCol(gamesResults[row]);
	}
	return translatedResults;
}

//this function builds the array that Oren requested
function buildCorrectResultsDisplayArray(gamesResults,row,col,game,correctResults){
	if (!game[row][col]) {//square is unmarked,
		if(col==translateCol(gamesResults[row])){ //square is unmarked, but in reality it was the result;
			return 3;
		}
		else{//square is unmarked, and in reality it wasn't the result;
			return 0;
		}
	}
	else{//if you are here - the square is marked	
		if(col==translateCol(gamesResults[row])){
			return 1; //it means the guess is correct
		}
		else{
			return 2;//it means the square is marked and incorrect
		}
	}
}

function refreshCost(){
	var price=getCost().toFixed(2);
	document.getElementById('cost_number').innerHTML = price;
}


//this function keeps the current data in the state as last week.
//need to change the idiot,prize etc. to getters (we shouldn't access the state directly);
function lastWeek(){
	var str=GamesStrState();
	var game = gameState();
	var results=correctResultsDisplayState();
	var agg_cost=getAggCost()+getCost();
	var agg_prize= getAggPrize()+parseInt(wave.getState().get("prize"));
	wave.getState().submitDelta({ 	"lw_game"  : wave.util.printJson( game ), //last week's filled form
		"lw_correctResultsDisplay": wave.util.printJson(results), //oren's results array from last week
		"lw_GamesStr" : str, //the names of last week's games
		"lw_prize"  : wave.getState().get("prize"), //how much money did the gruop win 
		"lw_idiotID" : wave.getState().get("idiotID"), //the id of last week's idiot
		"lw_hotID" : wave.getState().get("hotID"),
		"lw_cost" : wave.getState().get("cost"),
		"agg_prize": agg_prize,
		"agg_cost": agg_cost.toFixed(2),
		"lw_numberOfCorrectGuesses" : wave.getState().get("numberOfCorrectGuesses")}); 
}

/*function testMyLastWeek(){
		var id=wave.getState().get("lw_idiotID");
		alert("lastWeek"+lw_correctResultsDisplayState()[0][0]);
		alert("lastWeek"+lw_correctResultsDisplayState()[0][1]);
		alert("lastWeek"+lw_correctResultsDisplayState()[0][2]);
		if (id==-1) alert("lastWeek- no idiot");
		else alert("lastWeek:"+"idiot:"+wave.getParticipantById(wave.getState().get("lw_idiotID")).getDisplayName());
		alert("lastWeek:"+"guesses:"+wave.getState().get("lw_numberOfCorrectGuesses"));
		alert("lastWeek:"+"cost:"+wave.getState().get("lw_cost"));
		alert("lastWeek:"+"prize:"+wave.getState().get("lw_prize"));
		}*/


// the first call to init needs a NewForm() call
function firstInit(){
	var IsPlaying = parseInt(wave.getState().get("IsPlaying"));
	if(!IsPlaying){
		curTime = currentTime();
		if(	(curTime.getDay() ==0) ||
				(curTime.getDay() ==6) || 
				((curTime.getDay() ==1) && (curTime.getHours()< 7)) ||
				((curTime.getDay() ==5) && (curTime.getHours()> 11))) { 

			RefreshData(0);
			RefreshData(4);
		}
		getWaveIDfromDB();
		NewForm(0);
	}
}


/* enter the start day and end day and the function returns "true" if the current time is between start and end*/
function IsRightTime(start,end){
	var now = currentTime();
	if( now > start && now < end){
		return true;
	}
	else{
		return false;
	}
}

/*dates are stored as epoch time in the state. this getter will create a date object of a certain
   		  epoch time stored in "lable". if the label does not exist --> return a date 1/1/1970 00:00*/
function getDateFromState(label){
	d = parseInt(wave.getState().get(label));
	d = new Date(d);
	return d;
}		

function NewForm(flag){
	curTime = currentTime();
	if (flag==1) verifyWaveID(); // <Gili> added to support a case where we don't have a wave ID for some reason
	//alert(curTime.getDay());
	// while games are on - you cannot NewForm(). only reset the board.
	if(	(curTime.getDay() ==0) ||
			(curTime.getDay() ==6) || 
			((curTime.getDay() ==1) && (curTime.getHours()< 7)) ||
			((curTime.getDay() ==5) && (curTime.getHours()> 11))) { 
		doReset(1);
		//alert("just a board reset");
	}
	else{ // an actuall request for a new form on a legal day.
		var dateFromState = wave.getState().get("cellClickUpperLimit"); //need to use the function getDateFromState() here
		var currentGameDate = setToSpecificTime(5,12,0).getTime();
		if (currentGameDate!=parseInt(dateFromState)){//if this is an actuall time change related NewForm
			var arrayOfDates= getOldFormsListFromState();
			var gamesString=GamesStrState();  //this object will hold the games data.
			var formFillout= wave.util.printJson(gameState());; //this object will hold what we filled in the form.
			var crrectResults=wave.util.printJson(correctResultsDisplayState());//this object will hold the results
			var cost=getCost();
			var prize=wave.getState().get("prize");
			var numberOfCorrectGuesses=wave.getState().get("numberOfCorrectGuesses");
			var idiotID=wave.getState().get("idiotID");
			var hotID=wave.getState().get("hotID");
			
			RefreshData(0);//get the current games
			RefreshData(4);
			cellClickUpperLimit = setToSpecificTime(5,12,0); // cellclicks allowed only before friday, 12AM.
			cellClickLowerLimit = new Date(cellClickUpperLimit.getTime() - 4*86400000 -5*3600000);// and after monday , 7AM.
			resultsLowerLimit = setToSpecificTime(1,6,0);//results are in only on moday 6AM.
			resultsUpperLimit = new Date(resultsLowerLimit.getTime() + 6*86400000);//results are available for 6 days only.
			recommendationsUpperLimit = setToSpecificTime(0,18,30);// new recommendations are available between 
			recommendationsLowerLimit = new Date(recommendationsUpperLimit.getTime()-4*86400000); // wednesday 6:30PM and sunday 6:30PM.
			wave.getState().submitDelta({	"cellClickUpperLimit" : cellClickUpperLimit.getTime(),
				"cellClickLowerLimit" : cellClickLowerLimit.getTime(),
				"resultsUpperLimit"   : resultsUpperLimit.getTime(),
				"resultsLowerLimit"   : resultsLowerLimit.getTime(),
				"recommendationsUpperLimit" : recommendationsUpperLimit.getTime(),
				"recommendationsLowerLimit" : recommendationsLowerLimit.getTime(),
				"IsPlaying" : "1",
				"ResultsReq" : "0",
				"RecommendationsReq" : "0",
				"lastUpdatedTB" : "0"
			});
			if (flag==1){
				lastWeek(); //transfer the old data to lw labels in the state
				insertToOldFormList(dateFromState,arrayOfDates);			//<Gili>	puts the cellclickUpperLimit in the list of dates
				post(gamesString,formFillout,crrectResults,cost,prize,numberOfCorrectGuesses,idiotID,hotID);	//<Gili>	stores the form data in app engine
			}
		}
		doReset(1);
	}
}


function currentTime(){
	var D = new Date();
	//alert(d);
	return D;
}

//defines a date for wanted specific time in range of a week
function setToSpecificTime(day,hour,minute){
	var now = currentTime();
	var today = now.getDay();
	var daysDelta = ((day - today) < 0 ? (day - today + 7) : (day - today));
	var specificDate = new Date(now.getTime() + (86400000*daysDelta));
	specificDate.setHours(hour);
	specificDate.setMinutes(minute);
	specificDate.setSeconds(0,0);
	//make sure specific date is in the future
	var finalDate = ((specificDate < now) ? (new Date(specificDate.getTime() + (86400000*7))) : specificDate );
	return finalDate;
}

function RecommendationsToState(){
	if(IsRightTime(getDateFromState("recommendationsLowerLimit"),getDateFromState("recommendationsUpperLimit"))){
		RefreshData(2);
		wave.getState().submitDelta({ "RecommendationsReq" : "1"}); //for the display of recommendations
	}
}

function ResultsToState(){
	if(IsRightTime(getDateFromState("resultsLowerLimit"),getDateFromState("resultsUpperLimit"))){
		RefreshData(1);
		//wave.getState().submitDelta({ "ResultsReq" : "1"}); //for display of results
	}
}

//watch the state for debuging
function debug(){ 
	var s = wave.getState().toString();
	alert(s);
}




/********** appengine part ****************************/



// a special request bybasing cache
function makeCachedRequest(url, response, params, refreshInterval) {
	var ts = new Date().getTime();
	var sep = "?";
	if (refreshInterval && refreshInterval > 0) {
		ts = Math.floor(ts / (refreshInterval * 1000));
	}
	if (url.indexOf("?") > -1) {
		sep = "&";
	}
	url = [ url, sep, "nocache=", ts ].join("");
	gadgets.io.makeRequest(url, response, params);
}



/* 	getting data into the state: 	
			(type==0)-> games			 
			(type==1)-> results			
			(type==2)-> recommendations	 
			(type==3)-> returns the time and date string */


function RefreshData(type){
	var str;
	var	time;		
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		if(type==0){
			wave.getState().submitDelta({ "GamesStr" : str});
		}
		if(type==1){
			checkResults (str);
		}
		if(type==2){
			wave.getState().submitDelta({ "RecStr" : str});
		}
		if(type==3){
			wave.getState().submitDelta({ "TimeStr" : str});
		}
		if(type==4){
			wave.getState().submitDelta({ "StatLinksStr" : str});
		}		
	}

	var params = {};  
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
	var url;
	if(type==0){
		url = "http://gilivaturitest.appspot.com/gadgetRequestFormServlet"; 
	}
	if(type==1){
		url = "http://gilivaturitest.appspot.com/gadgetRequestResultsServlet";
	}
	if(type==2){
		url = "http://gilivaturitest.appspot.com/gadgetRequestRecServlet";
	}
	if(type==3){
		url = "http://gilivaturitest.appspot.com/gadgetRequestTimeServlet";
	}
	if(type==4){
		url = "http://gilivaturitest.appspot.com/gadgetRequestStatServlet";
	}
	makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh
}


/* 	this function updates the games,days and leagues.
		the GamesStr (taken from the state is) is a string containing all the data. 
		the string is saparated by 2 types of delimiters: 
		# - for spliting games from days,days from leagues.
		$ - for spilting within types of information(i.e. game1 from game2,day1 from day2 and so on).	*/		
function RefreshGames(){
	var GamesStr = GamesStrState();
	var games_arr;
	if(GamesStr && GamesStr!=""){
		var FieldsArray = GamesStr.split("#");
		FieldsArray = reverseArray(FieldsArray,3);
		for(j=3;j<6;j++){
			tempFieldArray = FieldsArray[j-3].split("$");
			for (i=0;i<16;i++){
				document.getElementById( "cell" + i + j ).innerHTML = tempFieldArray[15-i];
			}
		}
	}
}

/************ DEPRACATED FUNCTION
function RefreshRec(){
	if(parseInt(wave.getState().get("RecommendationsReq"))){ //if a request for recommendations was made
		TextRecArr = Recommendations(1);
		FinalRecArr = Recommendations(0);
		if(TextRecArr && FinalRecArr){
			var TempCell;
			for(i=0;i<16;i++){
				TempCell = document.getElementById( "tip" + i);
				TempCell.title = TextRecArr[15-i] + " " + FinalRecArr[15-i];
			}
		}
	}
	else{//clear the recommendations
		for(i=0;i<16;i++){
			TempCell = document.getElementById( "tip" + i);
			TempCell.title = "";
		}
	}
}****************************************************/

/*********	last week part 	************************/
/* Get last week's games*/
function LastWeekGamesStrState(){
	if ( wave.getState() ){
		var LastWeekGamesStr = wave.getState().get( "lw_GamesStr" );
		return LastWeekGamesStr ? LastWeekGamesStr : "";
	}
	else{
		return "";
	}
}

function RefreshLastWeekGames(LastWeekGamesStr){
	//var LastWeekGamesStr = LastWeekGamesStrState(); gili removed it
	if(LastWeekGamesStr && LastWeekGamesStr!=""){
		var FieldsArray = LastWeekGamesStr.split("#");
		FieldsArray = reverseArray(FieldsArray,3);
		for(j=3;j<6;j++){
			tempFieldArray = FieldsArray[j-3].split("$");
			for (i=0;i<16;i++){
				document.getElementById( "lw_cell" + i + j ).innerHTML = tempFieldArray[15-i];
			}
		}
	}
}


/* Put the cost,number of correct guesses & winnings in the last week div table*/	
function RefreshLastWeekStatistics(LastWeekCost,LastWeekMoney,LastWeekCorrectGuesses){
	//var LastWeekCost= wave.getState().get( "lw_cost" );
	if(LastWeekCost && LastWeekCost!=""){
		document.getElementById( "form_cost" ).innerHTML = LastWeekCost;
	}
	//var LastWeekMoney= wave.getState().get( "lw_prize" );
	if(LastWeekMoney && LastWeekMoney!=""){
		document.getElementById( "win_money" ).innerHTML = LastWeekMoney;    
	}
	//var LastWeekCorrectGuesses= wave.getState().get( "lw_numberOfCorrectGuesses" );
	if(LastWeekCorrectGuesses && LastWeekCorrectGuesses!=""){
		document.getElementById( "win_results" ).innerHTML = LastWeekCorrectGuesses;    
	} 

}
/* put the Idiot in the last week div table (Name and picture)*/
function RefreshLastWeekIdiot(LastWeekIdiotID,LastWeekHotID){
	//var LastWeekIdiotID= wave.getState().get( "lw_idiotID" ); //get idiot wave ID


	if(LastWeekIdiotID!="" && parseInt(LastWeekIdiotID)!=(-1)){
		var LastWeekIdiot=wave.getParticipantById(LastWeekIdiotID); //get idiot wave participant obj
		if (LastWeekIdiot && LastWeekIdiot!=""){
			document.getElementById( "lw_idiot_img" ).innerHTML ="<img src="+LastWeekIdiot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
			document.getElementById( "lw_idiot_name" ).innerHTML = LastWeekIdiot.getDisplayName();
		}
	}
	
	if(LastWeekHotID!="" && parseInt(LastWeekHotID)!=(-1)){
		var LastWeekHot=wave.getParticipantById(LastWeekHotID); //get idiot wave participant obj
		if (LastWeekHot && LastWeekHot!=""){
			document.getElementById( "lw_king_img" ).innerHTML ="<img src="+LastWeekHot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
			document.getElementById( "lw_king_name" ).innerHTML = LastWeekHot.getDisplayName();
		}
	}
	
}

/*Colors the 1 X 2 cells according to the last week results*/
function RefreshLastWeekCells(LastWeekCorrectResults){
	//ColorCell("lw_cell00",1);
	//ColorCell("lw_cell01",2);
	//var LastWeekCorrectResults = lw_correctResultsDisplayState(); removed by gili
	var cell;

	for (i=0;i<16;i++){
		for(j=0;j<3;j++){
			cell="lw_cell"+i+j;
			ColorCell(cell,parseInt(LastWeekCorrectResults[i][j]));

		}					
	} 

}

function RefreshResultsDisplay(){
	var CorrectResults = correctResultsDisplayState();
	var cell;

	for (i=0;i<16;i++){
		for(j=0;j<3;j++){
			cell="cell"+i+j;
			ColorCell(cell,parseInt(CorrectResults[i][j]));

		}					
	} 
}


/*Colors the cell : cell_id, according to the color recieved:
   color: 1=Green, 2=Red, 3=shaded Blue, 0=Blue*/
function ColorCell(cell_id,color){
	if (color==1) {
		document.getElementById(cell_id).setAttribute("class", "cellRight"); 
		return;
	}
	if (color==2) {
		document.getElementById(cell_id).setAttribute("class", "cellWrong");        
		return;
	}
	if (color==3) {
		document.getElementById(cell_id).setAttribute("class", "cellActuallGame");        
		return;
	}
	document.getElementById(cell_id).setAttribute("class", "cell");
}    

/*Updates all the Last Week information on its div, called from Last week button*/
function getLastWeekInfo(appEngineCellUpperLimit) {
	
	//if we enter the if it means we want to get the last week from the state, not from app engine
	if (appEngineCellUpperLimit==0){
	
	  document.getElementById("table_top_past_form").innerHTML= "שבוע שעבר : הטופס המלא ";
	   
		RefreshLastWeekGames(LastWeekGamesStrState()); //update the main table with the matches
		RefreshLastWeekStatistics(wave.getState().get( "lw_cost" ),wave.getState().get( "lw_prize" ),wave.getState().get( "lw_numberOfCorrectGuesses" )); //updates the cost,prize,num_of_correct_guesses
		RefreshLastWeekIdiot(wave.getState().get( "lw_idiotID" ),wave.getState().get( "lw_hotID" ));        //update the Idiot information (name&pic)
		RefreshLastWeekCells(lw_correctResultsDisplayState());     //update the table cells colors
	}
	else //when we enter the else it means that we want to get the data from app engine
	{
	getOldForm(appEngineCellUpperLimit);	
	}
}

/*********** talkback Part **********************************/
	//trimming Strings
	String.prototype.trim = function () {
		return this.replace(/^\s*/, "").replace(/\s*$/, "");
	}
	
	function submitTalkBack(gameNum){
		var TalkBackArray = getTalkBackArray();
		var newText = document.getElementById('newText'+gameNum).value;
		
		if(newText.trim() != ""){
			TalkBackArray[gameNum] = TalkBackArray[gameNum] +	
									"<div style='width:90%;'><p class='tb_us_name'>" +
									wave.getViewer().getDisplayName() + 
									": <p>" + newText +"</div>";
			str = TalkBackArray[0];
			for(i=1;i<16;i++){
				str = str + "#@&del" + TalkBackArray[i];
			}
			wave.getState().submitDelta({TalkBackString : str , lastUpdatedTB : gameNum});
			var newText = document.getElementById('newText'+gameNum).value="";//clearing the text area.
		}
	}

	function refreshTalkBacks(){
		var lastUpdatedTB = wave.getState().get("lastUpdatedTB");
		var TalkBackArray = getTalkBackArray();
		for(i=0 ; i<16 ; i++){
			document.getElementById('oldText' + i).innerHTML = "<div class='tb_title'> תגובות על המשחק: <b>" + document.getElementById("cell"+i+"3").innerHTML + "</b></div>" + TalkBackArray[i];
		}
		//resizing of the colorbox when needed
		if(document.getElementById('oldText' +lastUpdatedTB).offsetHeight < 400){
				$.fn.colorbox.resize();
		}	
	}
	
	
	function getTalkBackArray(){
		if ( wave.getState() ){
			var TalkBackArray = wave.getState().get("TalkBackString");//eval( "(" + wave.getState().get("TalkBackArray") + ")" );
			if(TalkBackArray){
				TalkBackArray = TalkBackArray.split("#@&del");
				return TalkBackArray;
			}
			else{
				return new Array("","","","","","","","","","","","","","","","");
			}
		}
		else{
			return new Array("","","","","","","","","","","","","","","","");
		}
	}
	
	function defaultTalkBackString(){
		return "#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del";
	}
   
   
/********** Design Part ********************************/
function goToHelp(){
	document.getElementById('familyPage').style.display = 'none';
	document.getElementById('helpPage').style.display = 'block';	
} 
function backToGame(){
	document.getElementById('helpPage').style.display = 'none';
	document.getElementById('familyPage').style.display = 'block';	
}
function newGameMouseOver() {
	document.getElementById('new_game_left').style.backgroundPosition = "left -32px";
	document.getElementById('new_game_right').style.backgroundPosition = "right -32px";
}
function newGameMouseOut() {
	document.getElementById('new_game_left').style.backgroundPosition = "left 0px";
	document.getElementById('new_game_right').style.backgroundPosition = "right 0px";
}
function lastWeekMouseOver() {
	document.getElementById('last_week_left').style.backgroundPosition = "left -32px";
	document.getElementById('last_week_right').style.backgroundPosition = "right -32px";
}
function lastWeekMouseOut() {
	document.getElementById('last_week_left').style.backgroundPosition = "left 0px";
	document.getElementById('last_week_right').style.backgroundPosition = "right 0px";
}
/********* Design Part End *******************************/

/******** NEW FUNTIONS **********************************/

/* This function was added by OREN */
/* The function changes the page that is being displayed according to the key "page"
    if page==1 then family mode is on
    if page==2 head2head mode is on
    if page is not defined, no mode was selected yet homepage will be shown*************************/
/*
    function getPage() {
      var display;
      /*This line should get 1 after someone clicked the "family page" link*/
/*display=parseInt(wave.getState().get("page"));

      if (display==1) {

        /* Show family page, hide homepage*/
/* document.getElementById('homePage').style.display = 'none';
  		  document.getElementById('familyPage').style.display = 'block';
        document.getElementById('blankPage').style.display = 'none';        
      }
      else {

        /* No Page was chosen, Show homepage*/
/*  document.getElementById('homePage').style.display = 'block';
        document.getElementById('blankPage').style.display = 'none';


      }      
    }
 */

var table = document.getElementById('content_table');

//this function gets x,y,z (amounts of clicks on 1,x,2) and displays a pie chart
function drawVisualization(x,y,z,game_num) {
	// Create and populate the data table.
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'Task');
	data.addColumn('number', 'Hours per Day');
	data.addRows(3);
	data.setValue(0, 0, 'משחקים שסומנו ב-1');
	data.setValue(0, 1, x);
	data.setValue(1, 0, 'משחקים שסומנו בתיקו');
	data.setValue(1, 1, y);
	data.setValue(2, 0, 'משחקים שסומנו ב-2');
	data.setValue(2, 1, z);

	// Create and draw the visualization.
	//var chart=new google.visualization.PieChart(document.getElementById('div'));
	var chart=new google.visualization.ImagePieChart(document.getElementById('real_time_stat_div'));
	//var options={width: 400, height: 240, is3D: true,enableTooltip: true, title: 'Guesses Distribution'};
	var colorsArray=new Array('#0076BE','#82C025','#F2AC08');
	var options={width: 380, height: 200, labels:'value',is3D: true,legend:'bottom',colors:colorsArray,title: (game_num + 1) + " שאל את הקהל! משחק מספר "};
	chart.draw(data,options);
}

//this function accesses the servlet that holds the populairty clicks, gets the information and invokes google visualization function
function drawChart(el){   
	var str;
	var	time;
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		var results= {};
		results=str.split("#");
		var x=parseInt(results[game_num*3]);
		var y=parseInt(results[(game_num*3)+1]);
		var z=parseInt(results[(game_num*3)+2]);
		drawVisualization(x,y,z,game_num);
	}
	
	var game_id = el.id;
  var game_num = parseInt(game_id.substr(5));

	var params = {}; 
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	var url="http://gilivaturitest.appspot.com/gadgetRequestTotoChart";
	makeCachedRequest(url, response, params,5); // 5 seconds till next cache refresh
}
/********************************************************************NEW VERSION FOR PROFILES********************************************************************/
function uniqueArray(arr) {
	var a = [];
    var l = arr.length;
    for(var i=0; i<l; i++){
      for(var j=i+1; j<l; j++){
        if (arr[i] === arr[j])
          j = ++i;
      }
      a.push(arr[i]);
    }
    return a;
 }
 
function checkResults (ResultsStr){
	
	var correctResultsDisplayArray=defaultCorrectResultsDisplay();	//gets a default array, no guesses on the board
	var gamesResults=Results(0,ResultsStr); 						//returns an array of actual results from the state
	var gamesMoney=Results(1,ResultsStr); 							//returns an array of of prizes from the state
	var game = gameState();											//returns the toto form state
	var account=accountState(); 									//returns the account state, which says which user filled which square
	var correctResults=defaultCorrectResults();						//this array will hold, for each game, did we win or lose
	var winningSquare=new Array();									//this array will hold the winning squares for each game
	var par=wave.getParticipants();									//creates an array (par) of the wave's participants
	var counter=0;
	var parHistory=parHistoryState();
	var last_week_money=0;											//init the prize won by the toto form
	var delta={};
	var scores=new Array();
	var totalScores=new Array();
	var sortedScores=new Array();
	var sortedTotalScores=new Array();
	
	function updateParHistory(value,type){
		if (type==0)
			str=parId+"_rightGuess";
		if (type==1)
			str=parId+"_wrongeGuess";
		if (type==2)
			str=parId+"_score";
		parHistory[str][0]=parHistory[str][0]+value;
		parHistory[str].push(value);
		delta[str]=wave.util.printJson(parHistory[str]);
	}
	//This function gets an array of participants (par) and returns an array with the hot's id in the first cell and the idiot's in the second
	function hotNot(scoresArray,sortedArray,flag){
		for ( i = 0; i < par.length; i++ ){
			var parId=par[i].getId();
			for ( j = 0; j < sortedArray.length; j++ ){
				if(scoresArray[parId]==sortedArray[j]){
					RS=sortedArray.length>1?j/(sortedArray.length-1):1;
					if (flag)
						parHistory[parId+"_place"].push(RS);
					else
						parHistory[parId+"_place"][0]=RS;	
					if (RS==1){
						if (flag)
							delta["hotID"]=parId;
						else
							delta["master_hotID"]=parId;
					}
					if ((RS==0)|(sortedArray.length==1)){
						if (flag)
							delta["idiotID"]=parId;
						else
							delta["master_idiotID"]=parId;
					}
				}
			}
			delta[parId+"_place"]=wave.util.printJson(parHistory[parId+"_place"]);	
		}
	}
	gamesResults=reverseArray(gamesResults,16); 					//reverse the array we get from Results(1);
	for ( row = 0; row <16 ; row++ ){
		winningSquare[row]=getWinnerCol(row,gamesResults);			//finds the winning square for each of the games
	}	
	for ( row = 0; row <16 ; row++ ){
		if (game[row][winningSquare[row]]){  						//in case we guessed the result correctly
			counter++;												//updates the count of correct results
			correctResults[row]=1;									//update the correct results array with the correct guess.
		}
		for ( col = 0; col < 3; col++ ){
				correctResultsDisplayArray[row][col]=buildCorrectResultsDisplayArray(gamesResults,row,col,game,correctResults);
		}
	}
	//this section was changed to fit the current profiles of 3x16 instead of 1x16
	for (iCR=0;iCR<par.length;iCR++){
		var rightGuess=0;
		var wrongeGuess=0;
		var parId=par[iCR].getId();
		var par_profile=profileState(parId);
		for ( row = 0; row <16 ; row++ ){
			for ( col = 0; col < 3; col++ ){
				if (col==winningSquare[row]){
					if (par_profile[row][col]==1)
						rightGuess++;
				}
				else{
					if (par_profile[row][col]==1)
						wrongeGuess++;
				}
			}		
		}
		
		var par_score=rightGuess-wrongeGuess;
		updateParHistory(rightGuess,0);
		updateParHistory(wrongeGuess,1);
		updateParHistory(par_score,2);
		totalScores[parId]=parHistory[parId+"_score"][0];
		scores[parId]=par_score;
		
		sortedScores.push(par_score);
		sortedTotalScores.push(totalScores[parId]);
		
	}
	sortedScores.sort(function(a,b){return a - b;});	//Sort numerically in descending order
	sortedTotalScores.sort(function(a,b){return a - b;});
	sortedScores=uniqueArray(sortedScores);
	sortedTotalScores=uniqueArray(sortedTotalScores);
	
	if (counter>12)
		last_week_money=gamesMoney[16-counter];
	
	hotNot(scores,sortedScores,true);
	hotNot(totalScores,sortedTotalScores,false);
	
	delta["ResultsReq"]="1";	 //for display of results
	delta["correctResultsDisplay"]=wave.util.printJson( correctResultsDisplayArray );
	delta["numberOfCorrectGuesses"]=counter;
	delta["prize"]=last_week_money;

	wave.getState().submitDelta(delta);
}

/*** NEW POST FUNCTIONS - ADDED BY OREN ****/
/*Get the HTML elemnt into which the IFrame will be inserted
returns the IFrame that was created*/  
function IFrame(parentElement)
{
   // Create the iframe which will be returned
   var iframe = document.createElement("iframe");

   // If no parent element is specified then use body as the parent element
   if(parentElement == null)
      parentElement = document.body;

   // This is necessary in order to initialize the document inside the iframe
   parentElement.appendChild(iframe);

   // Initiate the iframe's document to null
   iframe.doc = null;

   // Depending on browser platform get the iframe's document, this is only
   // available if the iframe has already been appended to an element which
   // has been added to the document
   if(iframe.contentDocument){
      // Firefox, Opera
      //alert("FF");
      iframe.doc = iframe.contentDocument;
      }
   else if(iframe.contentWindow){
      // Internet Explorer
      iframe.doc = iframe.contentWindow.document;
      //alert("IE")
      }
   else if(iframe.document) {
      // Others?
      //alert("Other");
      iframe.doc = iframe.document;
      }

   // If we did not succeed in finding the document then throw an exception
   if(iframe.doc == null)
      alert("Document not found, append the parent element to the DOM before creating the IFrame");

   // Create the script inside the iframe's document which will call the
   iframe.doc.open();
   iframe.doc.close();

   // Return the iframe, now with an extra property iframe.doc containing the
   // iframe's document
   return iframe;
}
 
  function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    var canvas = document.getElementById("canvas");
    var iframe = new IFrame(canvas);

    var form = iframe.doc.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        //var hiddenField = document.createElement("input");
        var hiddenField = iframe.doc.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
 
    }
    
    iframe.doc.body.appendChild(form);

    //document.body.appendChild(form);    
    form.submit();

}
function post(gamesString,formFillout,crrectResults,cost,prize,numberOfCorrectGuesses,idiotID,hotID){
    var url= "https://gilivaturitest.appspot.com/totoOldFormStorage"; //servlet address
    var dateFromState=wave.getState().get("cellClickUpperLimit");
	
	var waveID=wave.getState().get( "waveID" );
	var param=[];
    /*var gili="TEST_FF_FROM_WAVE";
	  for (i=0;i<1750;i++){
		gili=gili+i;
		}*/
	
	/*var gamesString=GamesStrState();  //this object will hold the games data.
	var formFillout= wave.util.printJson(gameState());; //this object will hold what we filled in the form.
	var crrectResults=wave.util.printJson(correctResultsDisplayState());//this object will hold the results
	var cost=getCost();
	var prize=wave.getState().get("prize");
	var numberOfCorrectGuesses=wave.getState().get("numberOfCorrectGuesses");
	var idiotID=wave.getState().get("idiotID");*/
	
	param['lorem']=gamesString+'*'+formFillout+'*'+crrectResults+'*'+cost+'*'+prize+'*'+numberOfCorrectGuesses+'*'+idiotID+'*'+hotID+'*'+"End";   //params is an Array of key's and their values
	param['ID']=waveID;
	param['date']=dateFromState;
    
    var meth="POST";                //Use POST method
    
    //setTimeout("post_to_url(url, param,meth)",500);
	post_to_url(url,param,meth);
    
    //$.post("https://totochartswebservice.appspot.com/totoOldFormStorage", { lorem : gili} );
            
}
//this function should be run only on the first init. it will create a unique waveID
function getWaveIDfromDB(){
	var str;		
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		//alert(str);
		wave.getState().submitDelta({ "waveID" : str});
	}

	var params = {};  
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
	var url="http://gilivaturitest.appspot.com/gadgetRequestWaveID";
	makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh

}

function getOldForm(appEngineCellUpperLimit){
var str;		
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		var appEngineArray = str.split("*");

		/*wave.getState().submitDelta( { "new_game"  : appEngineArray[1] });
		wave.getState().submitDelta( { "new_games_str"  : appEngineArray[0] });
		wave.getState().submitDelta( { "new_results"  : appEngineArray[2] });*/
		//alert(str);
		
		form_date=new Date(parseInt(appEngineCellUpperLimit));		
		document.getElementById("table_top_past_form").innerHTML= (form_date.toLocaleString());
				
		RefreshLastWeekGames(appEngineArray[0]); //update the main table with the matches
		RefreshLastWeekStatistics(appEngineArray[3],appEngineArray[4],appEngineArray[5]); //updates the cost,prize,num_of_correct_guesses
		RefreshLastWeekIdiot(appEngineArray[6],appEngineArray[7]);       //update the Idiot information (name&pic)
		RefreshLastWeekCells(eval( "(" + appEngineArray[2] + ")" ));     //update the table cells colors
		
		
	}

	var params = {};
	var waveID=wave.getState().get( "waveID" );	
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
	var url="http://gilivaturitest.appspot.com/gadgetRequestOldForm?"+waveID+"~"+appEngineCellUpperLimit;
	makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh
}

function insertToOldFormList(dateFromState,arrayOfDates){
		//var arrayOfDates= getOldFormsListFromState();
		//var dateFromState=wave.getState().get("cellClickUpperLimit");
		arrayOfDates.push(dateFromState);
		wave.getState().submitDelta( { "oldFormsList"  : wave.util.printJson( arrayOfDates )});
		}
		
	function testOldFormList(){
		
		var date;
		var oldForms= getOldFormsListFromState();
		for (i=0;i<oldForms.length;i++){
		date=new Date(parseInt(oldForms[i]))
		alert(oldForms[i]);
		alert(date);
		alert(date.toLocaleString());
		}
	}
		

	function verifyWaveID(){
		var waveID=parseInt(wave.getState().get( "waveID","0" ));
		if (!(waveID>0)) getWaveIDfromDB();
	}
	
	function loadStat(el){
  	var el_id = el.id;
    var el_num = el_id.substr(4);
    //alert(el_num);
    
    var stats_links_arr= StatURLsState();
    
  	//alert(stats_links_arr[15 - el_num]);
    document.getElementById("ifr_stat").src = stats_links_arr[15 - el_num];
    document.getElementById("tip_div").innerHTML = getRecByID(el_num);
  }

    function getRecByID(id){

     	var TempDiv="<h4> אין כרגע טיפ במערכת <br /> הטיפים מתפרסמים בכל יום רביעי </h4> ";
			
      if(parseInt(wave.getState().get("RecommendationsReq"))){ //if a request for recommendations was made
				TextRecArr = Recommendations(1);
				FinalRecArr = Recommendations(0);
				if((TextRecArr!="") && (FinalRecArr!="") && (TextRecArr[15-id]!=null) && (FinalRecArr[15-id]!=null)){
				  TempDiv="<h4> הטיפ שלנו: </h4> ";
					TempDiv +=  TextRecArr[15-id] + " ההימור שלנו: "+ FinalRecArr[15-id];
					alert("got in");
					}
				}
			
			return TempDiv;
		}
		//TEST FUNCTION FOR undefined BUG
		function createRec(){
		
		  wave.getState().submitDelta({ "RecommendationsReq" : "1"});
		  alert(null);
		  
      
    }
		
		/*This function adds 1 option to the select box of past forms*/
    function addItemToFormsTable(Text,Value)
    {
        // Create an Option object        
        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById("pastForms_select").options.add(opt);
        // Assign text and value to Option object
        opt.text = Text;
        opt.value = Value;

    }
    /* This function updates the form being viewed and it's relevant statistics on the history(last week) page*/
    function updateLastWeekGame(){
      //alert(document.getElementById("pastForms_select").value); 
      getLastWeekInfo(document.getElementById("pastForms_select").value);
    }
    
    /* This funcion updates the aggregated div info*/
    function updateLastWeekAggInfo(){
      var AggCost=getAggCost() ;
	    if(AggCost && AggCost!=""){
		  document.getElementById( "form_cost_agg" ).innerHTML = AggCost;
    	}
	   var AggPrize= getAggPrize();
	   if(AggPrize && AggPrize!=""){
	   document.getElementById( "win_money_agg" ).innerHTML = AggPrize;    
	   }
	
   // var LastWeekCorrectGuesses= wave.getState().get( "lw_numberOfCorrectGuesses" );
	 // if(LastWeekCorrectGuesses && LastWeekCorrectGuesses!=""){
		//document.getElementById( "win_results" ).innerHTML = LastWeekCorrectGuesses;    
	//}
	
	   //Update the aggregated idiot and hot picture and name
      var AggWeekIdiotID=wave.getState().get( "master_idiotID" );
      var AggWeekHotID=wave.getState().get( "master_hotID" );
    	
    		if(AggWeekIdiotID!="" && parseInt(AggWeekIdiotID)!=(-1)){
    		var AggWeekIdiot=wave.getParticipantById(AggWeekIdiotID); //get aggregated idiot wave participant obj
    		if (AggWeekIdiot && AggWeekIdiot!=""){
    			document.getElementById( "lw_idiot_img_agg" ).innerHTML ="<img src="+AggWeekIdiot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
    			document.getElementById( "lw_idiot_name_agg" ).innerHTML = AggWeekIdiot.getDisplayName();
    		}
    	}
    	
    	if(AggWeekHotID!="" && parseInt(AggWeekHotID)!=(-1)){
    		var AggWeekHot=wave.getParticipantById(AggWeekHotID); //get aggregated hot wave participant obj
    		if (AggWeekHot && AggWeekHot!=""){
    			document.getElementById( "lw_king_img_agg" ).innerHTML ="<img src="+AggWeekHot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
    			document.getElementById( "lw_king_name_agg" ).innerHTML = AggWeekHot.getDisplayName();
    		}
    	}
    	
    }
    
    /* This function updates the past forms select box with all the past forms*/  
    function createFormList(){

      if (select_box_updated==0){   //check that we didn't create the forms list yet
  
        var date;
    		var oldForms= getOldFormsListFromState();
      	for (i=0;i<oldForms.length;i++){
      		date=new Date(parseInt(oldForms[i]));
      		addItemToFormsTable(date.toLocaleString(),oldForms[i]);
      		
      		//alert(oldForms[i]);
      		//alert(date.toLocaleString());
      	}
      	select_box_updated=1;
      }
  		
    }
    
    /*This function updates all the information on the Team history page*/
    function openTeamHistory(){
		if(wave.getState().get("lw_game")){	
			getLastWeekInfo(0);         //updates last week form and statistics
			updateLastWeekAggInfo();    //updates the aggrageted info
			createFormList();           //updates the past form list  
			document.getElementById( "no_last_week" ).setAttribute("style","display:none;");
			document.getElementById("lastweek_content").setAttribute("style","display:block;");
		}
		else{
			document.getElementById( "no_last_week" ).setAttribute("style","display:block;");
			document.getElementById("lastweek_content").setAttribute("style","display:none;");
		}
	}
	
    /*This function clears the real time statistics div when closing color box*/
    function clearChart(){
      document.getElementById( "real_time_stat_div" ).innerHTML = ""; 
    }
